package com.foodorder.service;

import com.foodorder.entity.Store;
import com.foodorder.repository.StoreRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 店铺服务类
 */
@Service
@RequiredArgsConstructor
public class StoreService {
    
    private final StoreRepository storeRepository;
    
    /**
     * 查找附近的店铺
     */
    public List<Store> findNearbyStores(Double latitude, Double longitude, Double radius) {
        return storeRepository.findNearbyStores(latitude, longitude, radius);
    }
    
    /**
     * 按销量查找店铺
     */
    public Page<Store> findStoresByMonthlySales(Pageable pageable) {
        return storeRepository.findStoresByMonthlySales(pageable);
    }
    
    /**
     * 按评分查找店铺
     */
    public Page<Store> findStoresByRating(Pageable pageable) {
        return storeRepository.findStoresByRating(pageable);
    }
    
    /**
     * 搜索店铺
     */
    public Page<Store> searchStores(String keyword, Pageable pageable) {
        return storeRepository.searchStores(keyword, pageable);
    }
    
    /**
     * 根据ID查找店铺
     */
    public Store findById(Long id) {
        return storeRepository.findById(id).orElse(null);
    }
    
    /**
     * 查找所有营业中的店铺
     */
    public List<Store> findOpenStores() {
        return storeRepository.findByBusinessStatus(Store.BusinessStatus.OPEN);
    }
    
    /**
     * 计算配送信息（距离和预计时间）
     */
    public Map<String, Object> calculateDeliveryInfo(Long storeId, Double latitude, Double longitude) {
        // 简化版本：返回固定的距离和时间
        Double distance = 2.5; // 固定距离2.5公里
        
        Map<String, Object> deliveryInfo = new HashMap<>();
        deliveryInfo.put("distance", distance);
        
        // 简单的配送时间计算：基础时间20分钟 + 距离因子
        int estimatedMinutes = 20 + (int)(distance * 5); // 每公里增加5分钟
        deliveryInfo.put("estimatedDeliveryTime", estimatedMinutes);
        
        return deliveryInfo;
    }
    
    /**
     * 保存店铺
     */
    public Store save(Store store) {
        return storeRepository.save(store);
    }
    
    /**
     * 删除店铺
     */
    public void deleteById(Long id) {
        storeRepository.deleteById(id);
    }
    
    /**
     * 获取已审核通过的店铺（供顾客查看）
     */
    public List<Store> getApprovedStores() {
        return storeRepository.findByBusinessStatus(Store.BusinessStatus.OPEN);
    }
    
    /**
     * 获取商家的店铺
     */
    public List<Store> getStoresByMerchant(Long merchantId) {
        // 这里暂时返回所有店铺，实际应该根据merchantId查询
        return storeRepository.findAll();
    }
    
    /**
     * 获取所有店铺（供管理员查看）
     */
    public List<Store> getAllStores() {
        return storeRepository.findAll();
    }
    
    /**
     * 管理端分页查询店铺
     */
    public Page<Store> findStoresForAdmin(String keyword, String status, String city, Pageable pageable) {
        Specification<Store> spec = Specification.where(null);
        
        if (keyword != null && !keyword.trim().isEmpty()) {
            spec = spec.and((root, query, criteriaBuilder) -> 
                criteriaBuilder.or(
                    criteriaBuilder.like(root.get("name"), "%" + keyword + "%"),
                    criteriaBuilder.like(root.get("description"), "%" + keyword + "%")
                )
            );
        }
        
        if (status != null && !status.trim().isEmpty()) {
            try {
                Store.BusinessStatus businessStatus = Store.BusinessStatus.valueOf(status.toUpperCase());
                spec = spec.and((root, query, criteriaBuilder) -> 
                    criteriaBuilder.equal(root.get("businessStatus"), businessStatus)
                );
            } catch (IllegalArgumentException e) {
                // 忽略无效状态
            }
        }
        
        if (city != null && !city.trim().isEmpty()) {
            spec = spec.and((root, query, criteriaBuilder) -> 
                criteriaBuilder.like(root.get("address"), "%" + city + "%")
            );
        }
        
        return storeRepository.findAll(spec, pageable);
    }
    
    /**
     * 批量删除店铺
     */
    @Transactional
    public void deleteByIds(List<Long> ids) {
        storeRepository.deleteAllById(ids);
    }
    
    /**
     * 更新店铺状态
     */
    @Transactional
    public void updateStatus(Long id, String status) {
        Store store = storeRepository.findById(id)
            .orElseThrow(() -> new RuntimeException("店铺不存在"));
        
        try {
            Store.BusinessStatus businessStatus = Store.BusinessStatus.valueOf(status.toUpperCase());
            store.setBusinessStatus(businessStatus);
            storeRepository.save(store);
        } catch (IllegalArgumentException e) {
            throw new RuntimeException("无效的状态值: " + status);
        }
    }
    
    /**
     * 获取店铺统计信息
     */
    public Map<String, Object> getStoreStatistics() {
        Map<String, Object> statistics = new HashMap<>();
        
        // 总店铺数
        long totalStores = storeRepository.count();
        statistics.put("totalStores", totalStores);
        
        // 营业中店铺数
        long openStores = storeRepository.countByBusinessStatus(Store.BusinessStatus.OPEN);
        statistics.put("openStores", openStores);
        
        // 暂停营业店铺数
        long pausedStores = storeRepository.countByBusinessStatus(Store.BusinessStatus.PAUSED);
        statistics.put("pausedStores", pausedStores);
        
        // 关闭店铺数
        long closedStores = storeRepository.countByBusinessStatus(Store.BusinessStatus.CLOSED);
        statistics.put("closedStores", closedStores);
        
        return statistics;
    }
} 